<?php

namespace app\common\command;

use app\backstage\model\BalanceChange;
use app\backstage\model\CommissionRecord;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

use app\backstage\model\Order;
use app\backstage\model\Wallet;
use think\Exception;

class OrderDefine extends Command
{
    /**
     * 定义
     */
    protected function configure(){
        $this->setName('OrderDefine')->setDescription("计划任务  => Order Define");
    }

    /**
     * 执行
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     * @throws \Exception
     */
    public function execute(Input $input, Output $output)
    {
        $output->writeln('Date Crontab job start => Order Define');
        /*** 这里写计划任务列表集 START ***/

        $this->doDefine($output);

        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end => Order Define');
    }

    /**
     * 订单完成
     * @param Output $output
     * @throws \Exception
     */
    public function doDefine(Output $output)
    {
        $orderModel = app(Order::class);
        // 获取三天前的时间
//        $time = date('Y-m-d H:i:s', strtotime("-3 days"));
        $time = date('Y-m-d H:i:s');
        // 查询订单
        $orderList = $orderModel
            ->whereTime('finish_time', '<', $time)
            ->where('status', 7)
            ->select();
        foreach ($orderList as  $order) {
            $result = $this->handleDefineOrder($order);
            if (!$result['status']) {
                /*** 记录错误 ***/
                $output->writeln('订单号为 '.$order->order_sn.' 的订单自动完成失败！');
                $output->writeln('错误信息为： '.$result['msg']);
            }
        }
    }

    /**
     * 生成余额变动记录，自动完成订单
     * @param $order
     * @return array|bool
     */
    public function handleDefineOrder($order)
    {
        if (!in_array($order->status, [7])) {
            return ['status' => false, 'msg' => '订单状态已更改！'];
        }
        \Db::startTrans();
        try {
            $orderPrice = $order->order_price;
            $wallet  = new Wallet();
            $balance = $wallet->getValByCol(['uid' => $order->uid], 'balance');
            $change = new BalanceChange();
            $change->saveOne([
                'uid' => $order->uid,
                'order_id' => $order->id,
                'balance' => '-' . $orderPrice,
                'new_balance' => $balance - $orderPrice,
                'type' => 2
            ]);
            $wallet->where('uid',  $order->uid)->setDec( 'balance', $orderPrice);
            // 修改订单状态
            $order->status = 8;
            $order->save();
            \Db::commit();
            return ['status' => true, 'msg' => '修改成功'];
        } catch (Exception $exception) {
            \Db::rollback();
            return ['status' => false, 'msg' => $exception->getMessage()];
        }
    }

}